#!/usr/bin/env bash

# Copyright (c) 2024 ETH Zurich
#
# SPDX-License-Identifier: BSL-1.0
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

# ----------------------------------------------------------------
# simple pre commit hook script to check that *.cpp and *.hpp files
# are correctly clang-formatted and that CMakeLists.txt and *.cmake
# files are cmake-formatted

# To install this hook, symlink this hook to your git hooks as follows
# (note that the extra ../../ in the path is because git runs the hook
# from the .git/hooks directory, so the symlink has to be redirected)
# ln -s -f ../../tools/pre-commit-podman .git/hooks/pre-commit

# To use this hook, you must have podman installed.

# @todo : add support for the pika inspect tool to be run as well

function error_msg() {
    echo "$1 formatted files. run git add -u and git commit again."
    echo "run git commit --no-verify to bypass."
    git status
    exit_code=1
}

cont_image=docker.io/pikaorg/pika-ci-base:29
git_dir=$(git rev-parse --show-toplevel)

echo "Run clang-format"
podman run -w /pika/source -v=${git_dir}:/pika/source ${cont_image} \
    git-clang-format -f --extensions cpp,hpp,cu
result_clang_format=$?

echo "Run cmake-format"
checksum=$(git diff --cached --name-only | grep -E '(CMakeLists.txt|\.cmake)' | xargs -I {} sh -c 'md5sum {}')
podman run -w /pika/source -v=${git_dir}:/pika/source ${cont_image} \
    bash -c "git diff --cached --name-only | grep -E '(CMakeLists.txt|\.cmake)' | xargs cmake-format -i"
checksum_after_format=$(git diff --cached --name-only | grep -E '(CMakeLists.txt|\.cmake)' | xargs -I {} sh -c 'md5sum {}')

exit_code=0
if [ "$checksum" != "$checksum_after_format" ]; then
    error_msg "cmake-format"
fi
if [ "$result_clang_format" == 1 ]; then
    error_msg "clang-format"
fi

exit $exit_code
